package com.example.mall.user.svc.domain.service;

import com.example.mall.common.exception.BizException;
import com.example.mall.user.svc.app.cmd.BindCmd;
import com.example.mall.user.svc.infr.constants.LoginModeType;
import com.example.mall.user.svc.domain.model.entity.User;
import com.example.mall.user.svc.domain.model.vo.LoginMode;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author Mickey
 * @since 2022/4/17
 **/
@Component
public class BindMobile implements Bind {

    @Override
    public void bind(User user, BindCmd<?> bind) {
        String mobile = (String) bind.getData();
        user.setMobile(mobile);
        List<LoginMode> loginModes = user.getLoginModes();
        for (LoginMode loginMode : loginModes) {
            LoginModeType type = loginMode.getType();
            if (type == LoginModeType.MOBILE) {
                throw new BizException("重复绑定");
            }
        }
        loginModes.add(new LoginMode(mobile, LoginModeType.MOBILE));
    }

    @Override
    public void unbind(User user, BindCmd<?> bind) {
        List<LoginMode> loginModes = user.getLoginModes();
        loginModes.removeIf(s -> s.getType() == LoginModeType.MOBILE);
        user.setMobile("");
    }

    @Override
    public void change(User user, BindCmd<?> bind) {
        String mobile = (String) bind.getData();
        List<LoginMode> loginModes = user.getLoginModes();
        for (LoginMode loginMode : loginModes) {
            LoginModeType type = loginMode.getType();
            if (type == LoginModeType.MOBILE) {
                loginMode.setUniqueId(mobile);
                user.setMobile(mobile);
            }
        }
    }
}
